<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>实时音频</title>
    <meta
      name="viewport"
      content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"
    />
    <!-- <link href="css/index.css" rel="stylesheet" /> -->
    <link href="js/layer/need/layer.css" rel="stylesheet" />
    <script src="js/jquery-2.2.4.min.js"></script>
    <script src="js/qiniu-QNRTC/es6-promise.js?v=1.0"></script>
    <script src="js/qiniu-QNRTC/pili-rtc-web.js?v=1.0"></script>
    <script src="js/layer/layer.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      html,
      body {
        position: relative;
        width: 100%;
        height: 100%;
      }
      body {
        background: #000;
      }
      .btn {
        border: none;
        padding: 0 15px;
        border-radius: 5px;
        background: linear-gradient(to bottom, #fb7e76, #ff0202);
        line-height: 25px;
        color: #fff;
        width: 200px;
        position: absolute;
        bottom: 209px;
        right: 10px;
        width: 100px;
      }
      .qnrtc-stream-player {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
      .fullscreen-player {
        width: 100vw;
        height: 100vh;
        position: absolute;
        top: 0;
        left: 0;
        background: #000;
      }
      .mini-player {
        width: 160px;
        height: 180px;
        position: absolute;
        bottom: 10px;
        right: 10px;
        background: #000;
        z-index: 10;
        border: 1px solid #eee;
      }

      .cancel {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background-color: #ff0202;
        font-size: 16px;
        text-align: center;
        line-height: 60px;
        position: absolute;
        bottom: 5%;
        left: calc(50% - 30px);
        z-index: 88;
        color: #fff;
      }

      /* audio 元素 */
      audio {
        visibility: hidden;
      }

      /* video 元素 */
      video {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .contacting {
        position: absolute;
        width: 100%;
        z-index: 99;
        height: 40px;
        line-height: 40px;
        font-size: 16px;
        color: #fff;
        bottom: calc(50% - 20px);
        text-align: center;
      }

    </style>
    <script>
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?cb5d49b07e0a753dc8ee27ba2c73495d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  </head>
  <body>
    <div id="localplayer" class="mini-player"></div>

    <div id="remoteplayer" class="fullscreen-player">
    </div>

    <button class="btn screen-switch" onclick="switchScreen()">
      大小窗切换
    </button>

    <div onclick="leaveRoom()" class="cancel">挂断</div>


    <div class="contacting"></div>

    <script>
      var roomToken = GetQueryString("roomToken");
      var type = GetQueryString("type");
      var istrue;
      if (type == 0) {
        $("#localplayer").hide();
        $("#remoteplayer").hide();
        $(".btn").hide();
        istrue = false;
        $(".contacting").text('语音通话连接中...');
        // layer.open({ content: "进入语音通话！", skin: "msg", time: 2 });
      } else if (type == 1) {
        // layer.open({ content: "进入视频通话！", skin: "msg", time: 2 });
        $(".contacting").text('视频通话连接中...');
        istrue = true;
      }
      // var roomToken =
      //   "dZ4JiqyNgc6WgVEixLPUSzrEr3jUloZewEuV4gJI:_stWx2r9_VAtMIrtG8n_Xzm8XYo=:eyJhcHBJZCI6ImV4aGpoM2I3YiIsInVzZXJJZCI6NDUsInJvb21OYW1lIjo0NTU2fQ==";
      var myRTC = new QNRTC.QNRTCSession();

      function subscribeUser(myRTC, user) {
        // 如果用户没有发布就直接返回
        if (!user.published) {
          return;
        }
        // 注意这里订阅使用了 Promise 的写法而没有用 async/await
        // 因为在我们 Demo 中并没有依赖订阅这个操作的后续操作
        // 即没有操作必须等到订阅操作结束之后再运行
        myRTC
          .subscribe(user.userId)
          .then((remoteStream) => {
            // 我们在 room 页面上准备用来显示远端媒体流的元素
            layer.open({
              content: '已接通！',
              skin: "msg",
              time: 2, //2秒后自动关闭
            });
            if(type == 0){
              $(".contacting").text('正在进行语音通话...');
            }else{
              $('.contacting').hide();

            }
            var remotePlayer = document.getElementById("remoteplayer");
            // 在我们准备的元素上播放远端媒体流
            remoteStream.play(remotePlayer);
          })
          .catch((e) => {
            console.log("subscribe error!", e);
          });
      }

      (async () => {
        try {
          // 调用 SDK 加入房间
          var users = await myRTC.joinRoomWithToken(roomToken);
          console.log("joinRoom success! 当前房间用户:", users);

          // 采集本地媒体流，视频和音频都采集
          var localStream = await QNRTC.deviceManager.getLocalStream({
            video: { enabled: istrue, width: 160, height: 180, bitrate: 600 },
            audio: { enabled: true, bitrate: 32 }
          });

          // if (istrue) {
            // 获取我们 room.html 中准备用来显示本地媒体流的元素
            var localPlayer = document.getElementById("localplayer");
            // 调用媒体流的 play 方法，在我们指定的元素上播放媒体流，其中第二个参数代表 静音播放
            localStream.play(localPlayer, true);
            // 发布刚刚采集到的媒体流到房间
            await myRTC.publish(localStream);
          // }

          // window.onbeforeunload = () => {
          //   myRTC.leaveRoom();
          // };

          // var users = await myRTC.joinRoomWithToken(roomToken);
          // console.log("joinRoom success! 当前房间用户:", users);

          // 监听房间里的用户发布事件，一旦有用户发布，就订阅他
          myRTC.on("user-publish", (user) => {
            myRTC.setMergeStreamLayout(user.userId, {
              x: 0,
              y: 0,
              w: document.body.offsetWidth,
              h: document.body.offsetHeight,
              hidden: false,
              muted: false
            });
            subscribeUser(myRTC, user);
          });
          // 判断房间当前的用户是否有可以订阅的
          for (let i = 0; i < users.length; i += 1) {
            var user = users[i];
            // 如果当前房间的用户不是自己并且已经发布
            // 那就订阅他
            if (user.published && user.userId !== myRTC.userId) {
              subscribeUser(myRTC, user);
            }
          }
        } catch (e) {
          console.log("error!", e);
        }
      })();
      //离开房间
      function leaveRoom() {
        myRTC.leaveRoom();
        //返回上一页
        window.history.back();
      }

      function switchScreen() {
        console.info("---switchScreen-----");
        var localPlayer = document.getElementById("localplayer");
        var remotePlayer = document.getElementById("remoteplayer");
        // 交换 2 个元素的 class
        if (localPlayer.className === "mini-player") {
          localPlayer.className = "fullscreen-player";
          remotePlayer.className = "mini-player";
        } else {
          localPlayer.className = "mini-player";
          remotePlayer.className = "fullscreen-player";
        }
      }

      //接收地址栏参数
      function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
      }
    </script>
  </body>
</html>
